import { useState, useEffect } from 'react'
import { Play, Square, Plus, Trash2, Zap, Settings } from 'lucide-react'
import { toast } from 'react-hot-toast'
import type { FieldConfig, DataGeneratorConfig, FieldType } from '@/types/dataGenerator'
import { dataGeneratorApi } from '@/services/dataGenerator'
import TopicSelector from '@/components/kafka/TopicSelector'

interface DataGeneratorPanelProps {
  topics: string[]
  selectedTopic: string
  onTopicChange: (topic: string | null) => void
  onProgress?: (progress: any) => void
}

interface GeneratorProgress {
  task_id: string
  topic: string
  total_count: number
  sent_count: number
  status: string
  progress_percent: number
  error_message?: string
}

export default function DataGeneratorPanel({ topics, selectedTopic, onTopicChange, onProgress }: DataGeneratorPanelProps) {
  const [isGenerating, setIsGenerating] = useState(false)
  const [progress, setProgress] = useState<GeneratorProgress | null>(null)
  const [fieldTypes, setFieldTypes] = useState<FieldType[]>([])
  
  const [config, setConfig] = useState<DataGeneratorConfig>({
    topic: selectedTopic,
    fields: [
      { name: 'id', type: 'uuid', options: {} },
      { name: 'name', type: 'name', options: {} },
      { name: 'email', type: 'email', options: {} },
      { name: 'created_at', type: 'datetime', options: { current: true } }
    ],
    count: 100,
    interval: 1000,
    batch_size: 1,
    stream_mode: true
  })

  useEffect(() => {
    setConfig(prev => ({ ...prev, topic: selectedTopic }))
  }, [selectedTopic])

  useEffect(() => {
    loadFieldTypes()
    checkCurrentStatus()
  }, [])

  useEffect(() => {
    // 监听WebSocket消息
    const handleWebSocketMessage = (event: MessageEvent) => {
      try {
        const message = JSON.parse(event.data)
        if (message.type === 'data_generator_progress') {
          const progressData = message.data
          setProgress(progressData)
          
          if (progressData.status === 'completed') {
            setIsGenerating(false)
            toast.success(`数据生成完成！共发送 ${progressData.sent_count} 条消息`)
          } else if (progressData.status === 'failed') {
            setIsGenerating(false)
            toast.error(`数据生成失败: ${progressData.error_message}`)
          } else if (progressData.status === 'stopped') {
            setIsGenerating(false)
            toast.info('数据生成已停止')
          }
          
          onProgress?.(progressData)
        }
      } catch (error) {
        // 忽略非JSON消息
      }
    }

    if (window.ws) {
      window.ws.addEventListener('message', handleWebSocketMessage)
      return () => {
        window.ws?.removeEventListener('message', handleWebSocketMessage)
      }
    }
  }, [onProgress])

  const loadFieldTypes = async () => {
    try {
      const response = await dataGeneratorApi.getFieldTypes()
      setFieldTypes(response.field_types)
    } catch (error) {
      console.error('加载字段类型失败:', error)
    }
  }

  const checkCurrentStatus = async () => {
    try {
      const response = await dataGeneratorApi.getCurrentStatus()
      if (response.status === 'active') {
        setIsGenerating(true)
        setProgress(response.task)
      }
    } catch (error) {
      console.error('检查任务状态失败:', error)
    }
  }

  const startGeneration = async () => {
    if (!selectedTopic) {
      toast.error('请先选择Topic')
      return
    }

    if (config.fields.length === 0) {
      toast.error('请至少添加一个字段')
      return
    }

    // 验证字段名称
    const fieldNames = config.fields.map(f => f.name)
    const duplicateNames = fieldNames.filter((name, index) => fieldNames.indexOf(name) !== index)
    if (duplicateNames.length > 0) {
      toast.error(`字段名称重复: ${duplicateNames.join(', ')}`)
      return
    }

    const emptyNames = config.fields.filter(f => !f.name.trim())
    if (emptyNames.length > 0) {
      toast.error('请填写所有字段名称')
      return
    }

    try {
      const requestData = {
        ...config,
        topic: selectedTopic,
        // 确保数据类型正确
        count: Number(config.count),
        interval: Number(config.interval),
        batch_size: Number(config.batch_size),
        stream_mode: Boolean(config.stream_mode)
      }

      console.log('发送数据生成请求:', requestData)
      await dataGeneratorApi.startGeneration(requestData)
      setIsGenerating(true)
      setProgress(null)
      toast.success('数据生成已启动')
    } catch (error: any) {
      console.error('启动数据生成失败:', error)
      let errorMessage = '启动数据生成失败'

      if (error.response?.data?.detail) {
        if (typeof error.response.data.detail === 'string') {
          errorMessage = error.response.data.detail
        } else if (Array.isArray(error.response.data.detail)) {
          errorMessage = error.response.data.detail.map((err: any) => err.msg || err).join(', ')
        } else {
          errorMessage = '请求参数验证失败'
        }
      } else if (error.message) {
        errorMessage = error.message
      }

      toast.error(errorMessage)
    }
  }

  const stopGeneration = async () => {
    try {
      await dataGeneratorApi.stopCurrentTask()
      setIsGenerating(false)
      toast.info('数据生成已停止')
    } catch (error: any) {
      console.error('停止数据生成失败:', error)
      let errorMessage = '停止数据生成失败'

      if (error.response?.data?.detail) {
        if (typeof error.response.data.detail === 'string') {
          errorMessage = error.response.data.detail
        } else {
          errorMessage = '停止任务失败'
        }
      } else if (error.message) {
        errorMessage = error.message
      }

      toast.error(errorMessage)
    }
  }

  const addField = () => {
    setConfig(prev => ({
      ...prev,
      fields: [...prev.fields, { name: '', type: 'string', options: {} }]
    }))
  }

  const removeField = (index: number) => {
    setConfig(prev => ({
      ...prev,
      fields: prev.fields.filter((_, i) => i !== index)
    }))
  }

  const updateField = (index: number, field: Partial<FieldConfig>) => {
    setConfig(prev => ({
      ...prev,
      fields: prev.fields.map((f, i) => i === index ? { ...f, ...field } : f)
    }))
  }

  return (
    <div className="card">
      <div className="card-header">
        <div className="flex items-center space-x-2">
          <Zap className="w-5 h-5 text-purple-600" />
          <h2 className="card-title">数据生成器</h2>
        </div>
        <p className="card-description">
          自动生成测试数据并发送到Kafka Topic
        </p>
      </div>
      <div className="card-content space-y-6">

        {/* Topic选择 */}
        <div>
          <label className="block text-sm font-medium text-gray-700 mb-2">
            目标Topic *
          </label>
          <TopicSelector
            topics={topics}
            selectedTopic={selectedTopic}
            onTopicChange={onTopicChange}
            placeholder="选择要发送数据的Topic"
          />
        </div>

        {/* 进度显示 */}
        {progress && (
          <div className="p-4 bg-gray-50 rounded-lg border">
            <div className="flex justify-between items-center mb-2">
              <span className="text-sm font-medium text-gray-700">
                生成进度: {progress.sent_count} / {progress.total_count}
              </span>
              <span className="text-sm font-medium text-gray-700">
                {progress.progress_percent}%
              </span>
            </div>
            <div className="w-full bg-gray-200 rounded-full h-2">
              <div
                className={`h-2 rounded-full transition-all duration-300 ${
                  progress.status === 'completed' ? 'bg-green-500' :
                  progress.status === 'failed' ? 'bg-red-500' :
                  'bg-purple-500'
                }`}
                style={{ width: `${progress.progress_percent}%` }}
              />
            </div>
            {progress.error_message && (
              <div className="mt-2 text-sm text-red-600">
                错误: {progress.error_message}
              </div>
            )}
          </div>
        )}

        {/* 基本配置 */}
        <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              生成数量
            </label>
            <input
              type="number"
              min="1"
              max="10000"
              className="input"
              value={config.count}
              onChange={(e) => setConfig(prev => ({ ...prev, count: Number(e.target.value) }))}
            />
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              发送间隔(毫秒)
            </label>
            <input
              type="number"
              min="100"
              max="60000"
              step="100"
              className="input"
              value={config.interval}
              onChange={(e) => setConfig(prev => ({ ...prev, interval: Number(e.target.value) }))}
            />
          </div>

          <div className="flex items-end">
            <label className="flex items-center space-x-2">
              <input
                type="checkbox"
                checked={config.stream_mode}
                onChange={(e) => setConfig(prev => ({ ...prev, stream_mode: e.target.checked }))}
                className="rounded border-gray-300 text-purple-600 focus:ring-purple-500"
              />
              <span className="text-sm text-gray-700">流式发送</span>
            </label>
          </div>
        </div>

        {/* 字段配置 */}
        <div>
          <div className="flex items-center justify-between mb-3">
            <label className="block text-sm font-medium text-gray-700">
              字段配置 *
            </label>
            <button
              type="button"
              onClick={addField}
              className="btn btn-outline btn-sm"
              disabled={isGenerating}
            >
              <Plus className="w-4 h-4 mr-1" />
              添加字段
            </button>
          </div>

          <div className="space-y-3">
            {config.fields.map((field, index) => (
              <div key={index} className="p-4 border border-gray-200 rounded-lg bg-gray-50">
                <div className="grid grid-cols-1 md:grid-cols-3 gap-3">
                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-1">字段名称</label>
                    <input
                      type="text"
                      className="input input-sm"
                      placeholder="字段名称"
                      value={field.name}
                      onChange={(e) => updateField(index, { name: e.target.value })}
                      disabled={isGenerating}
                    />
                  </div>

                  <div>
                    <label className="block text-xs font-medium text-gray-600 mb-1">字段类型</label>
                    <select
                      className="input input-sm"
                      value={field.type}
                      onChange={(e) => updateField(index, { type: e.target.value, options: {} })}
                      disabled={isGenerating}
                    >
                      {fieldTypes.map(ft => (
                        <option key={ft.type} value={ft.type}>
                          {ft.description}
                        </option>
                      ))}
                    </select>
                  </div>

                  <div className="flex items-end">
                    <button
                      type="button"
                      onClick={() => removeField(index)}
                      className="btn btn-outline btn-sm text-red-600 hover:bg-red-50 border-red-200"
                      disabled={isGenerating}
                    >
                      <Trash2 className="w-4 h-4" />
                    </button>
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        {/* 操作按钮 */}
        <div className="flex items-center justify-between pt-4 border-t">
          <div className="text-sm text-gray-500">
            生成的数据将包含 _generated_at 和 _generator_id 元数据字段
          </div>

          {isGenerating ? (
            <button
              onClick={stopGeneration}
              className="btn btn-danger"
            >
              <Square className="w-4 h-4 mr-2" />
              停止生成
            </button>
          ) : (
            <button
              onClick={startGeneration}
              disabled={!selectedTopic}
              className="btn btn-primary"
            >
              <Play className="w-4 h-4 mr-2" />
              开始生成
            </button>
          )}
        </div>
      </div>
    </div>
  )
}
